//
//  ThreeView.swift
//  swiftTS
//
//  Created by 航电 on 2020/3/4.
//  Copyright © 2020 航电. All rights reserved.
//

import UIKit

typealias onClickBlock = (Int) -> Void;

class ThreeView: UIView {

    var pictureArray = NSMutableArray();
    var mainScrollView : UIScrollView?;
    var pageCtl:UIPageControl?;
    var timer:Timer?;

    var clickBlock:onClickBlock?;
    
    override init(frame: CGRect) {
        super.init(frame: frame);
        
        self.onCreateUIForView();
        
        self.onAddTimer();
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //TODO:UI
    func onCreateUIForView() {
        self.backgroundColor = .lightGray;
        
        self.mainScrollView = UIScrollView(frame: self.bounds);
        self.mainScrollView?.backgroundColor = .clear;
        self.mainScrollView?.isPagingEnabled = true;
        self.mainScrollView?.bounces = false;
        self.mainScrollView?.showsVerticalScrollIndicator = false;
        self.mainScrollView?.showsHorizontalScrollIndicator = false;
        self.mainScrollView?.delegate = self;
        self.addSubview(self.mainScrollView!);
        
        self.pageCtl = UIPageControl(frame: CGRect(x: 0, y: (self.mainScrollView?.frame.size.height)!-30, width: (self.mainScrollView?.frame.size.width)!, height: 30));
        self.pageCtl?.pageIndicatorTintColor = .blue;
        self.pageCtl?.currentPageIndicatorTintColor = .red;
        self.insertSubview(self.pageCtl!, aboveSubview: self.mainScrollView!);
    }

    func onAddTimer() {
        self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(onTimerForScrollView), userInfo: nil, repeats: true);
        RunLoop.current.add(self.timer!, forMode: .common);
    }
    
    //TODO:Actions
    public func onAddPitureForVC(picArr:NSArray) {
        self.pictureArray.removeAllObjects();
        self.pictureArray.addObjects(from: picArr as! [Any]);
        
        if picArr.count > 1 {
            self.pictureArray.insert(picArr.lastObject!, at: 0);
            self.pictureArray.add(picArr.firstObject!);
        }
        
        self.onCreateUIForScrollView();
    }
    
    func onCreateUIForScrollView() {
        
        //清除子视图
        self.mainScrollView?.subviews.forEach({ (subView) in
            subView.removeFromSuperview();
        });
        
        //添加子视图
        let mainScrollViewWidth = self.mainScrollView?.frame.size.width;
        let mainScrollViewHeight = (self.mainScrollView?.frame.size.height)!;
        for index in 0 ... self.pictureArray.count-1 {
            let imgView = UIImageView(frame: CGRect(x: CGFloat(index)*mainScrollViewWidth!, y: 0, width: mainScrollViewWidth!, height: mainScrollViewHeight));
            imgView.backgroundColor = .clear;
            imgView.image = UIImage(named: self.pictureArray.object(at: index) as! String);
            imgView.contentMode = .scaleAspectFit;
            imgView.tag = 400 + index;
            imgView.isUserInteractionEnabled = true;
            self.mainScrollView?.addSubview(imgView);
            
            let tapGestureation = UITapGestureRecognizer(target: self, action: #selector(onTapForImageView(tap:)));
            imgView.addGestureRecognizer(tapGestureation);
        }
        
        let contentSizeWidth = CGFloat(self.pictureArray.count) * mainScrollViewWidth! ;
        self.mainScrollView?.contentSize = CGSize(width: contentSizeWidth, height: mainScrollViewHeight);
        if self.pictureArray.count > 1 {
            self.mainScrollView?.setContentOffset(CGPoint(x: mainScrollViewWidth!,y: 0), animated: true);
        }
        
        self.pageCtl?.numberOfPages = (self.pictureArray.count > 1 ? self.pictureArray.count-2 : 1);
        self.pageCtl?.currentPage = 0;
    }
    
    @objc func onTimerForScrollView() {
    let mainScrollViewWidth = self.mainScrollView!.frame.size.width;
    
    print("一直在打印>>");
    var offSetX = Int((self.mainScrollView?.contentOffset.x ?? 0) / mainScrollViewWidth);
    offSetX += 1;
    
    //最后一张图片
    if offSetX == self.pictureArray.count-1 {
        UIView.animate(withDuration: 0.25, animations: {
            self.mainScrollView?.setContentOffset(CGPoint(x: CGFloat(offSetX)*mainScrollViewWidth,y: 0), animated: true);
            self.pageCtl?.currentPage = 0;
        }) { (isFinish) in
            self.mainScrollView?.setContentOffset(CGPoint(x: mainScrollViewWidth,y: 0), animated: false);
        };
    } else {
        UIView.animate(withDuration: 0.25, animations: {
            self.mainScrollView?.setContentOffset(CGPoint(x: CGFloat(offSetX)*mainScrollViewWidth,y: 0), animated: true);
            self.pageCtl?.currentPage = offSetX-1;
        }) { (isFinish) in
            self.pageCtl?.currentPage = offSetX-1;
        };
    }
}
    
    func onClickImageForBlock(ckBlock:@escaping (Int)->Void) {
        self.clickBlock = ckBlock;
    }
    
    @objc func onTapForImageView(tap:UITapGestureRecognizer) {
        if self.clickBlock != nil {
            self.clickBlock!(tap.view!.tag);
        }
    }
    
    public func destroyTimer() {
        if self.timer != nil {
            self.timer?.invalidate();
            self.timer = nil;
        }
    }
}

extension ThreeView:UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let mainScrollViewWidth = scrollView.frame.size.width;
        let offSetX = Int(scrollView.contentOffset.x / mainScrollViewWidth);
        if offSetX == 0 {
            self.pageCtl?.currentPage = self.pictureArray.count-3;
        } else if offSetX == (self.pictureArray.count-1) {
            self.pageCtl?.currentPage = 0;
        } else {
            self.pageCtl?.currentPage = offSetX-1;
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if self.timer != nil {
            self.timer?.fireDate = NSDate.distantFuture;
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        if self.timer != nil {
            self.timer?.fireDate = NSDate(timeIntervalSinceNow: 2) as Date;
        }
        
        let mainScrollViewWidth = scrollView.frame.size.width;
        let offSetX = Int(scrollView.contentOffset.x / mainScrollViewWidth);
        print(">>第\(offSetX)个");
        if offSetX == 0 {
            self.mainScrollView?.setContentOffset(CGPoint(x: CGFloat(self.pictureArray.count-2)*mainScrollViewWidth,y: 0), animated: false);
            self.pageCtl?.currentPage = self.pictureArray.count-3;
        } else if offSetX == (self.pictureArray.count-1) {
            self.mainScrollView?.setContentOffset(CGPoint(x: mainScrollViewWidth,y: 0), animated: false);
            self.pageCtl?.currentPage = 0;
        } else {
            self.pageCtl?.currentPage = offSetX-1;
        }
        
    }
}
